<script setup>
import {onMounted, ref} from "vue";
import api from "../../libs/api.js";
import FormBox from "../FormBox.vue";

const props = defineProps({
  agent: {
    type: Object,
    required: true,
    default: () => ({
      id: null,
      name: '',
      agentType: '',
      note: '',
      icon: ''
    })
  }
});
const config = ref({
  id: 0,
  agentId: props.agent.id,
  dbDriverClassName: '',
  dbUrl: '',
  dbUsername: '',
  dbPassword: '',
  databases: []
});
const loading = ref(false);
onMounted(() => {
  console.log(props.agent)
  loading.value = true;
  api.get(`/api/v1/agent/${props.agent.id}/database-config`)
    .then(res => {
      config.value = res.data.responseBody;
      console.log('Agent config fetched:', config.value);
      if (config.value.databases.length > 0) {
        selectedDatabase.value = config.value.databases[0];
      }
    })
    .catch(err => {
      console.error('Failed to fetch agent config:', err);
    }).finally(() => {;
      loading.value = false;
    });
})

const deleteDatabases = (db) => {
  if (selectedDatabase.value === db) {
    selectedDatabase.value = null;
  }
  config.value.databases = config.value.databases.filter(item => item.databaseName !== db.databaseName);
}
const addDatabase = () => {
  const databaseName = prompt("请输入数据库名称");
  if (!databaseName) {
    alert("数据库名称不能为空");
    return;
  }
  if (config.value.databases.some(item => item.databaseName === databaseName)) {
    alert("数据库名称已存在");
    return;
  }
  api.post(`/api/v1/agent/${props.agent.id}/database-config/${databaseName}`, config.value)
    .then(res => {
      config.value.databases.push(res.data.responseBody);
      selectedDatabase.value = res.data.responseBody;
    });
}
const selectedDatabase = ref(null);

const saveConfig = () => {
  // 构建本地配置
  config.value.databases.forEach(db => {
    db.tables = [];
    db.fullTables.forEach(table => {
      if (table.selected) {
        let columns = [];
        table.columns.forEach(column => {
          if (column.selected) {
            columns.push({
              columnName: column.columnName,
              columnType: column.columnType,
              description: column.description || ''
            });
          }
        });
        db.tables.push({
          tableName: table.tableName,
          description: table.description,
          columns: columns
        });
      }
    });
  });

  // 保存
  return api.put(`/api/v1/agent/${props.agent.id}/database-config`, config.value);
}
defineExpose({
  saveConfig
});
</script>

<template>
<div class="database-agent-setting">
  <div class="database-agent-loading" v-if="loading">
    <div class="loading-text">正在连接数据库, 请稍后...</div>
  </div>
  <form-box title="数据源配置">
    <div class="database-setting-form">
      <div class="form-item">
        <label for="dbDriverClassName">数据库驱动类名:</label>
        <input type="text" id="dbDriverClassName" v-model="config.dbDriverClassName" />
      </div>
      <div class="form-item">
        <label for="dbUrl">数据库连接URL:</label>
        <input type="text" id="dbUrl" v-model="config.dbUrl" />
      </div>
      <div class="form-item">
        <label for="dbUsername">数据库用户名:</label>
        <input type="text" id="dbUsername" v-model="config.dbUsername" />
      </div>
      <div class="form-item">
        <label for="dbPassword">数据库密码:</label>
        <input type="password" id="dbPassword" v-model="config.dbPassword" autocomplete="new-password"/>
      </div>
    </div>
  </form-box>

  <div class="database-setting-databases" style="margin-top: 20px;">
    <form-box style="flex: 1" title="可访问的数据库">
      <div style="display: flex; flex: 1">
        <div class="left-database-list">
          <div class="add-btn" @click="addDatabase">添加数据库</div>
          <div class="left-database-list-scroll">
            <div class="database-item" v-for="db in config.databases"
                 :key="db.databaseName" @click="selectedDatabase = db" :class="{ 'active': selectedDatabase === db }">
              <div class="database-name">{{ db.databaseName }}</div>
              <div class="database-delete-btn" @click="deleteDatabases(db)">删除</div>
            </div>
          </div>
        </div>
        <div class="right-database-options">
          <div v-if="selectedDatabase" class="database-tables">
            <div class="database-table" v-for="table in selectedDatabase.fullTables" :key="table.tableName"
                 v-if="selectedDatabase.fullTables && selectedDatabase.fullTables.length > 0">
              <div class="database-table-header">
                <div class="table-name">{{ table.tableName }}</div>
                <div class="table-selected">
                  <input type="checkbox" v-model="table.selected" />
                </div>
              </div>
              <input type="text" class="table-description" v-model="table.description" placeholder="表描述" />
              <ul>
                <li v-for="column in table.columns" :key="column.columnName" class="table-column">
                  <div class="column-name">{{ column.columnName }}</div>
                  <div class="column-type">{{ column.columnType }}</div>
                  <input type="text" class="column-description" v-model="column.description" placeholder="字段描述" />
                  <div class="column-selected">
                    <input type="checkbox" v-model="column.selected" />
                  </div>
                </li>
              </ul>
            </div>
            <div v-if="selectedDatabase.fullTables.length === 0" class="no-tables">
              <p>当前数据源中没有该数据库, 或当前数据源中的用户没有该数据库的任何表访问权限, 请核实。</p>
            </div>
          </div>
          <div v-else>
            <p>请在左侧选择一个数据库。</p>
          </div>
        </div>
      </div>
    </form-box>
  </div>
</div>
</template>

<style scoped lang="less">
.database-agent-setting{
  width: 80vw;
  height: 80vh;
  display: flex;
  flex-direction: column;
  position: relative;

  .database-agent-loading{
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: rgba(255, 255, 255, 0.8);
    z-index: 1000;

    .loading-text{
      font-size: 16px;
      color: #333;
      background-color: rgba(255, 255, 255, 0.8);
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
      display: flex;
      justify-content: center;
      align-items: center;
      width: 300px;
      height: 100px;
      border: 1px solid #e4e4e4;
      backdrop-filter: blur(5px);
      transition: opacity 0.3s ease;
      opacity: 1;
    }


  }

  input{
    outline: none;
    &:focus{
      border-color: #007bff!important;
    }
  }

  .database-setting-form{
    display: flex;
    flex-direction: column;
    width: 100%;
    .form-item{
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      label{
        width: 150px;
      }
      input{
        flex-grow: 1;
        padding: 5px;
        border-radius: 4px;
        border: 1px solid #ccc;
      }
    }
  }

  .database-setting-databases{
    flex: 1;
    display: flex;
    .left-database-list{
      width: 250px;
      border: 1px solid #e4e4e4;
      display: flex;
      flex-direction: column;

      .add-btn{
        padding: 10px;
        background-color: #f0f0f0;
        text-align: center;
        cursor: pointer;
        &:hover {
          background-color: #e0e0e0;
        }
      }
      .left-database-list-scroll{
        flex: 1;
        overflow-y: auto;
        padding: 10px;

        .database-item{
          display: flex;
          justify-content: space-between;
          padding: 10px;
          border: 1px solid #e4e4e4;
          cursor: pointer;
          &.active{
            border: 1px solid #007bff;
          }
          .database-name{
            font-weight: bold;
          }
          .database-delete-btn{
            color: red;
            cursor: pointer;
          }
        }
      }
    }
    .right-database-options{
      flex: 1;
      padding: 10px;
      background-color: #f9f9f9;

      .database-tables{
        height: calc(80vh - 260px);
        overflow-y: auto;

        .database-table{
          margin-bottom: 20px;
          padding: 10px;
          background-color: white;
          border: 1px solid #e4e4e4;
          border-radius: 5px;

          .database-table-header{
            display: flex;
            justify-content: space-between;
            align-items: center;
            .table-selected{
              display: flex;
              align-items: center;
            }

            .table-name{
              font-weight: bold;
              margin-bottom: 10px;
            }
          }


          .table-description{
            width: 100%;
            padding: 5px;
            margin-bottom: 10px;
            border-radius: 4px;
            border: 1px solid #ccc;
          }
          .table-column{
            display: flex;
            justify-content: space-between;
            margin-bottom: 5px;

            .column-name{
              font-weight: bold;
              width: 200px;
            }
            .column-type{
              width: 150px;
            }
            .column-description{
              flex-grow: 1;
              padding: 5px;
              border-radius: 4px;
              border: 1px solid #ccc;
            }
            .column-selected{
              display: flex;
              align-items: center;
            }
          }
        }
      }
    }
  }
}
</style>
